import React, { PureComponent } from 'react';
import { connect, routerRedux } from 'dva';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { message, Form } from 'antd';
import 'moment/locale/zh-cn';
import { DATA_ENTRY, AdvancedSearch, TableC, FormItemLayout } from '../../../components';
import style from './index.less';

@connect(({ monitorpublicopinionM, globalM, loading }) => ({
  monitorpublicopinionM,
  globalM,
  loading,
}))
export default class SecSearchC extends PureComponent {
  state = {
    timeOutGap: 500,
    currentPage: 1, // news当前页码
    numInPage: 10, // 每页数量
    secSearch: {
      analysisType: '0',
      affection: '2',
    }, // 二级查询条件
    secReset: false, // 是否点击二级重置按钮
    type: '0', // 0新闻 1公告
  };

  componentDidMount() {
    this.props.onRef(this);
    if (!sessionStorage.getItem('riskNews')) {
      this.queryTableList();
    }
  }

  componentWillUnmount() {
    // 离开前清除models数据
    this.props.dispatch({
      type: 'monitorpublicopinionM/setState',
      payload: {
        noticeTableColumns: undefined, // 公告列表表头
        noticeTableData: undefined, // 公告列表数据
        noticeTotal: 0, // 公告列表总条数
        newsTableColumns: undefined, // 新闻列表表头
        newsTableData: undefined, // 新闻列表数据
        newsTotal: 0, // 新闻列表总条数
      },
    });
  }

  showValue = (arr, value) => {
    if (!arr.length) return '--';
    let text = '';
    arr.forEach((item) => {
      if (item.code === value) {
        text = item.value;
      } else if (value > 3) {
        text = '非常重要';
      }
    });
    return text || '--';
  };

  // 查询表格数据
  queryTableList = (e) => {
    const { dispatch, type } = this.props;
    const { secSearch, numInPage, currentPage } = this.state;
    if (e) {
      this.setState({
        secSearch: e,
      });
    }
    const obj = e ? e : secSearch;

    if (type == '0') {
      this.props.dispatch({
        type: 'monitorpublicopinionM/setState',
        payload: {
          newsTableColumns: undefined,
          newsTableData: undefined,
          newsTotal: 0,
        },
      });
    } else {
      this.props.dispatch({
        type: 'monitorpublicopinionM/setState',
        payload: {
          noticeTableColumns: undefined, // 公告列表表头
          noticeTableData: undefined, // 公告列表数据
          noticeTotal: 0, // 公告列表总条数
        },
      });
    }
    const apiParams = {
      ...obj,
      currentPage,
      numInPage,
    };

    if (type == '0') {
      dispatch({
        // 查询新闻列表
        type: 'monitorpublicopinionM/comNewsList',
        payload: { ...apiParams },
      });
    } else {
      dispatch({
        // 查询公告列表
        type: 'monitorpublicopinionM/comAnnouncement',
        payload: { ...apiParams },
      });
    }
  };

  // 展示表格
  showTable = () => {
    const {
      globalM: {
        dataDictionary: { COMPANY_IMPORTANCE = [], COMPANY_AFFECTION = [] },
      },
    } = this.props;
    const {
      type,
      loading,
      monitorpublicopinionM: { noticeTableColumns, noticeTableData, noticeTotal, newsTableColumns, newsTableData, newsTotal },
    } = this.props;
    const { currentPage, numInPage } = this.state;
    let columns;
    type == '0' ? (columns = newsTableColumns) : (columns = noticeTableColumns);
    columns &&
      columns.map((item) => {
        if (item.key == 'noticeTitle' || item.key == 'newsTitle') {
          item.render = (text, record) => {
            return <a onClick={() => this.showInfo(record)}>{text}</a>;
          };
        }
        if (item.key == 'importantLevel') {
          item.render = (text, record) => {
            return this.showValue(COMPANY_IMPORTANCE, text);
          };
        }
        if (item.key == 'affection') {
          item.render = (text, record) => {
            return this.showValue(COMPANY_AFFECTION, text);
          };
        }
        if (item.key == 'noticeType') {
          item.render = (text, record) => {
            if (text) {
              return text.join(',');
            } else {
              return '--';
            }
          };
        }
      });
    const data = type == '0' ? newsTableData : noticeTableData;
    return (
      <div style={{ marginTop: '20px' }}>
        <TableC
          columns={columns}
          dataSource={type == '0' ? newsTableData : noticeTableData}
          total={type == '0' ? newsTotal : noticeTotal}
          hidePage={true}
          rowKey='key'
          loading={loading.effects['monitorpublicopinionM/comNewsList'] === true || loading.effects['monitorpublicopinionM/comAnnouncement'] === true}
        />

        <div className={style.pageBtn}>
          <span
            title={'上一页'}
            onClick={() => {
              this.pageChange('pre');
            }}
            className={currentPage == 1 ? 'ant-pagination-disabled ant-pagination-prev' : 'ant-pagination-prev'}
          >
            <a style={{ width: '100%' }} className='ant-pagination-item-link'>
              <LeftOutlined />{' '}
            </a>
          </span>
          <span
            title={'下一页'}
            onClick={() => {
              this.pageChange('next');
            }}
            className={data && data.length < numInPage ? 'ant-pagination-disabled  ant-pagination-next' : ' ant-pagination-next'}
          >
            <a style={{ width: '100%' }} className='ant-pagination-item-link'>
              <RightOutlined />
            </a>
          </span>
        </div>
      </div>
    );
  };

  // 页码跳转
  pageChange = (changeType) => {
    const { currentPage, secReset, numInPage } = this.state;
    const {
      type,
      monitorpublicopinionM: { noticeTableData, newsTableData },
    } = this.props;
    const data = type == '0' ? newsTableData : noticeTableData;
    if (data.length < numInPage && changeType == 'next') return;
    if (changeType == 'pre') {
      if (currentPage == 1) return;
    }
    if (secReset) {
      // 判断一级按钮或二级按钮点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    this.setState(
      {
        currentPage: changeType == 'pre' ? currentPage - 1 : currentPage + 1,
      },
      () => {
        this.queryTableList();
      },
    );
  };

  // 跳转至详情页
  showInfo = (row) => {
    const obj = {
      bondID: row.id,
      type: this.props.type == '0' ? 'news' : 'notice',
      comid: row.comcode,
    };
    this.props.type == '0' ? null : sessionStorage.setItem('noticeInfo', JSON.stringify(row));
    sessionStorage.setItem('publicSentiment', JSON.stringify(obj));
    this.props.dispatch({
      // 触发willReceiveProps
      type: 'monitorpublicopinionM/setState',
      id: row.id,
    });
    this.props.type == '0'
      ? this.props.dispatch(routerRedux.push(`/marketAnalysis/Monitorpublicopinion/newsDetail`))
      : this.props.dispatch(routerRedux.push(`/marketAnalysis/Monitorpublicopinion/noticeDetail`));
  };

  // 父组件点击重置按钮 调用该方法
  resetForm = () => {
    this.searchRef.handleReset();
    this.setState({
      secReset: false,
    });
  };

  // 事件标签搜索
  onSearch = (v) => {
    // v是当前输入的值
    const props = this.props.monitorpublicopinionM;
    const arr = [];
    if (!v) {
      // 无数据时 默认展示20条
      this.props.dispatch({
        type: 'monitorpublicopinionM/setState',
        payload: {
          eventLabelList: props.oEventLabelList.slice(0, 20),
        },
      });
      return;
    }
    props.oEventLabelList.forEach((e, i) => {
      if (e.value.indexOf(v) >= -0) {
        arr.push(e);
      }
    });
    this.props.dispatch({
      type: 'monitorpublicopinionM/setState',
      payload: {
        eventLabelList: arr.length ? arr.slice(0, 20) : props.oEventLabelList,
      },
    });
  };

  // 主体名称模糊搜索
  queryComcode = (e) => {
    const { dispatch } = this.props;
    const { timeOutGap } = this.state;
    if (e) {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        dispatch({
          type: 'monitorpublicopinionM/queryComcode',
          payload: {
            name: e,
          },
        });
      }, timeOutGap);
    }
  };

  // 公告类型搜索
  noticeTypeSearch = (v) => {
    // v是当前输入的值
    const props = this.props.monitorpublicopinionM;
    const arr = [];
    if (!v) {
      // 无数据时 默认展示20条
      this.props.dispatch({
        type: 'monitorpublicopinionM/setState',
        payload: {
          noticeTypeList: props.oNoticeTypeList.slice(0, 20),
        },
      });
      return;
    }
    props.oNoticeTypeList.forEach((e, i) => {
      if (e.title.indexOf(v) >= -0) {
        arr.push(e);
      }
    });
    this.props.dispatch({
      type: 'monitorpublicopinionM/setState',
      payload: {
        noticeTypeList: arr.length ? arr.slice(0, 20) : props.oNoticeTypeList,
      },
    });
  };

  render() {
    const {
      loading,
      type,
      analysisType,
      monitorpublicopinionM: { noticeTypeList, eventLabelList, comcodeList },
    } = this.props;
    const {
      globalM: {
        dataDictionary: { COMPANY_IMPORTANCE = [], COMPANY_AFFECTION = [], COMPANY_ANALYSIS_TYPE = [] },
      },
    } = this.props;
    const { secSearch } = this.state;
    const eventList = [...eventLabelList.slice(0, 20)];
    const noticeList = [...noticeTypeList.slice(0, 20)];
    const data =
      type == '0'
        ? [
            {
              dataIndex: 'comcode',
              title: '主体名称',
              type: DATA_ENTRY.SELECT,
              dataSource: comcodeList,
              filterOption: false,
              placeholder: '请输入',
              allowClear: true,
              optionTitle: true,
              onSearch: (e) => {
                this.queryComcode(e);
              },
              loading: loading.effects['monitorpublicopinionM/queryComcode'] === true,
            },
            {
              dataIndex: 'mainNews',
              title: '关键字',
              type: DATA_ENTRY.INPUT,
              formItemLayout: FormItemLayout,
            },
            {
              dataIndex: 'analysisType',
              title: '分析类型',
              type: DATA_ENTRY.SELECT,
              dataSource: COMPANY_ANALYSIS_TYPE.map((item) => {
                return {
                  value: item.code,
                  title: item.value,
                };
              }),
              initialValue: secSearch.analysisType,
            },
            {
              dataIndex: 'importantLevel',
              title: '重要性',
              type: DATA_ENTRY.SELECT,
              allowClear: true,
              formItemLayout: FormItemLayout,
              dataSource: COMPANY_IMPORTANCE.map((item) => {
                return {
                  value: item.code,
                  title: item.value,
                };
              }),
            },
            {
              dataIndex: 'eventLabel',
              title: '事件标签',
              type: DATA_ENTRY.SELECT,
              dataSource: eventList,
              allowClear: true,
              formItemLayout: FormItemLayout,
              optionTitle: true,
              onSearch: (e) => {
                this.onSearch(e);
              },
              filterOption: false,
            },
            {
              dataIndex: 'affection',
              title: '情感倾向',
              type: DATA_ENTRY.SELECT,
              dataSource: COMPANY_AFFECTION.map((item) => {
                return {
                  value: item.code,
                  title: item.value,
                };
              }),
              initialValue: '2',
              allowClear: true,
              formItemLayout: FormItemLayout,
            },
          ]
        : [
            {
              dataIndex: 'comcode',
              title: '主体名称',
              type: DATA_ENTRY.SELECT,
              dataSource: comcodeList,
              filterOption: false,
              placeholder: '请输入',
              allowClear: true,
              optionTitle: true,
              onSearch: (e) => {
                this.queryComcode(e);
              },
              loading: loading.effects['monitorpublicopinionM/queryComcode'] === true,
            },
            {
              dataIndex: 'noticeTitle',
              title: '关键字',
              type: DATA_ENTRY.INPUT,
              formItemLayout: FormItemLayout,
            },
            {
              dataIndex: 'analysisType',
              title: '分析类型',
              type: DATA_ENTRY.SELECT,
              dataSource: COMPANY_ANALYSIS_TYPE.map((item) => {
                return {
                  value: item.code,
                  title: item.value,
                };
              }),
              initialValue: secSearch.analysisType,
            },
            {
              dataIndex: 'noticeType',
              title: '公告类型',
              type: DATA_ENTRY.SELECT,
              dataSource: noticeList,
              isMultiple: true,
              allowClear: true,
              formItemLayout: FormItemLayout,
              optionTitle: true,
              onSearch: (e) => {
                this.noticeTypeSearch(e);
              },
              filterOption: false,
            },
          ];
    const searchProps = {
      dataSource: data,
      onQuery: (e) => {
        this.setState(
          {
            secSearch: e,
            secReset: false,
            currentPage: 1,
          },
          () => {
            this.queryTableList(); // 点击查询按钮
          },
        );
      },
      onClear: () => {
        // 点击重置按钮
        if (sessionStorage.getItem('resetFlag') != null) {
          // 判断是不是父组件调用的，父组件调用为否，自己调用为是
          sessionStorage.removeItem('resetFlag');
          this.setState({
            secReset: false,
          });
        } else {
          this.setState({
            secReset: true,
          });
        }
        if (type == '0') {
          this.setState({
            secSearch: {
              analysisType: '0',
              affection: '2',
            },
          });
        } else {
          this.setState({
            secSearch: {
              analysisType: '0',
            },
          });
        }
      },
      onRef: (ref) => {
        this.searchRef = ref;
      },
    };
    return (
      <div>
        <div className='cardBody'>
          <AdvancedSearch {...searchProps} />
        </div>
        {this.showTable()}
      </div>
    );
  }
}
